
import {
  PageContainer,
  ProColumnType,
  ProFormInstance,
} from '@ant-design/pro-components';
import {
  ProCard,
  ProTable,
} from '@ant-design/pro-components';
import {Button, message, Popconfirm} from 'antd';
import { useRef, useState } from 'react';
import {DataType, interfaceColumns} from "@/pages/Manage/columns/interfaceColumns";
import {DeleteOutlined, PlusOutlined, PoweroffOutlined, QuestionCircleOutlined, ToolOutlined} from "@ant-design/icons";
import InterfaceModalForm from "@/pages/Manage/IntroduceManage/components/InterfaceModalForm";
import {
  addInterfaceInfoUsingPost, deleteInterfaceInfoUsingPost,
  listInterfaceInfoVoByPageUsingPost, updateInterfaceInfoUsingPost
} from "@/services/yuanapi_backed/interfaceInfoController";





const IntroduceManage = () => {
  const ref = useRef<ProFormInstance>();
  const [updateModalForm,setUpdateModalForm] =  useState<boolean>(false)
  const [addModalForm,setAddModalForm] =  useState<boolean>(false)
  // const [data,setData] = useState<API.PageInterfaceInfoVO_>({})
  const[loading,setLoading] = useState<boolean>(true)
  const [currentData,setCurrentData] = useState<API.InterfaceInfoVO>({})


  // 添加接口
  const handleAdd = async (values : API.InterfaceInfoAddRequest)=>{
    try {
      const res  = await addInterfaceInfoUsingPost({
        ...values,
      })
      if (res.code === 0){
        message.success('添加成功')
        setLoading(false)
      }
    }
    catch (e:any){
      message.error('添加失败')
      message.error(e.message)
    }
  }
  // 修改接口
  const  handleUpdate = async (values: API.InterfaceInfoUpdateRequest,id:any) => {
    try {
      const res = await updateInterfaceInfoUsingPost({
        ...values,
        id:id,
      })
      if (res.code === 0) {
        message.success('修改成功')
        setLoading(false)
      }
    } catch (e: any) {
      message.error('修改失败')
      message.error(e.message)
    }

  }

  // 下线
  const handleOffline = async (record: API.InterfaceInfoVO) => {
    try {
      const res = await updateInterfaceInfoUsingPost({
        description:record.description,
        interfaceName:record.interfaceName,
        requestExample:record.requestExample,
        requestHeader:record.requestHeader,
        requestMethod:record.requestMethod,
        requestParams:record.requestParams,
        url:record.url,
        id: record.id,
        // status 接口状态 0 代表 已发布 1 代表下线
        status: 1,
      })
      if (res.code === 0) {
        message.success('下线成功')
        setLoading(false)
      }
    } catch (e: any) {
      message.error('下线失败')
      message.error(e.message)
    }
  }
  // 删除
  const handleDelete = async (record: API.InterfaceInfoVO) => {
    try {
      const res = await deleteInterfaceInfoUsingPost({
        id: record.id,
      })
      if (res.code === 0) {
        message.success('删除成功')
        setLoading(false)
      }
    } catch (e: any) {
      message.error('删除失败')
      message.error(e.message)
    }
  }


  const columns: ProColumnType<DataType>[] = [
    ...interfaceColumns,
    {
      title: '操作',
      key: 'action',
      sorter: true,
      valueType: 'option',
      width:100,
      render: (_, record) => (
        <>
          <Button key="Update" type="primary" icon={<ToolOutlined /> } style={{marginTop:5 ,marginRight:5}} onClick={()=>{
            setCurrentData(record)
            setUpdateModalForm(true)
          }}>修改</Button>
          <Popconfirm
            title="下线"
            key="UpdatePopconfirm"
            description="确定要下线该接口吗?"
            icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
            onConfirm={()=>handleOffline(record)}
          >
          <Button danger  key="Offline" icon={<PoweroffOutlined />} style={{marginTop:5}} >下线</Button>
          </Popconfirm>
            <Popconfirm
            title="删除"
            key="DeletePopconfirm"
            description="确定要删除该接口吗?"
            icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
            onConfirm={()=>handleDelete(record)}
          >
          <Button danger   key="Delete" icon={<DeleteOutlined />} style={{marginTop:5}}>删除</Button>
          </Popconfirm>
        </>
      )
    },
  ];

  const initData = {
    bordered: true,
    // loading: loading,
    columns,
    // pagination: {
    //   show: true,
    //   pageSize: 10,
    // },
    size: 'large',
    expandable: false,
    headerTitle: '接口管理',
    tooltip: '接口管理 tooltip',
    showHeader: true,
    footer: true,
    rowSelection: {},
    scroll: false,
    hasData: true,
    tableLayout: undefined,
    toolBarRender: true,
    search: {
      show: true,
      span: 8,
      collapseRender: true,
      labelWidth: 80,
      filterType: 'query',
      layout: 'horizontal',
    },
    options: {
      show: true,
      density: true,
      fullScreen: true,
      setting: true,
    },
  };
  const [config] = useState<any>(initData);
  const tableColumns = (config.columns || columns)?.map((item: any) => ({
    ...item,
    ellipsis: config.ellipsis,
  }));

  return (
    <PageContainer >
    <ProCard
      split="vertical"
      bordered
      headerBordered
      style={{
        height: '100vh',
        overflow: 'hidden',
      }}
    >
      <ProCard
        style={{
          height: '100vh',
          overflow: 'auto',
        }}
      >
        <ProTable
          {...config}
          // loading={loading}
          formRef={ref}
          pagination={
            config.pagination?.show
              ? config.pagination
              : {
                pageSize: 10,
              }
          }
          search={config.search?.show?config.search : {}}
          expandable={
            config.expandable && {
              expandedRowRender: (record: DataType) => (
                <p>{record.description}</p>
              ),
            }
          }
          options={config.options?.show ? config.options : false}
          toolBarRender={
            config?.toolBarRender
              ? () => [
                <Button key="add" type="primary" icon={<PlusOutlined />} onClick={()=>{setAddModalForm(true)}}>
                  新增
                </Button>,
              ]
              : false
          }
          footer={config.footer ? () => '接口返回的类型均应为JSON类型哦' : false}
          headerTitle={config.headerTitle}
          columns={tableColumns}
          // dataSource={genData(config.pagination?.total || 10)}
          scroll={config.scroll}
          request={async (  params:  {
            describe : string;
            interfaceName: string;
            status:number;
            pageSize: string;
            current: string;
          },) => {
            setLoading(true)
            const res = await listInterfaceInfoVoByPageUsingPost({
              ...params
              });
            // console.log(res)
            if (res.data) {
              // setData(res.data)
              setLoading(false)
              return {
                data: res.data.records || [],
                success: true,
                total: res.data.total,
              };
            } else {
              return {
                data: [],
                success: false,
                total:0
              };
            }
          }}
        />
        <InterfaceModalForm
          title = {"修改接口"}
          open={updateModalForm}
          key='updateModalForm'
          onCancel={() => setUpdateModalForm(false)}
          onOpenChange={setUpdateModalForm}
          onSubmit={async (values )=>{
            await handleUpdate(values,currentData.id)
        }
        }
          values={currentData}
        />

        <InterfaceModalForm
          key='AddModalForm'
          title = {"添加接口"}
          open={addModalForm}
          onCancel={() => setAddModalForm(false)}
          onOpenChange={setAddModalForm}
          onSubmit={async (values )=>{
            await handleAdd(values)
          }
        }
         values={{}}
        />
      </ProCard>
    </ProCard>
    </PageContainer>
  );
};

export default IntroduceManage;
